from mtp.lib.plugin import Plugin
from mtp.lib.base import *
from datetime import datetime

from lxml.builder import ElementMaker
from lxml import etree


class RSSController(BaseController):
    def get(self, page_id):
        page = model.Page.getByTitle(page_id)
        if not page: abort(404)

        E = ElementMaker()

        items = []
        for revision in page.revisions:
            author = revision.author.username if revision.author else ''
            items.append(E.item(
                E.title('%s:%s %s' % (revision.title, 
                                      revision.revision, 
                                      author)),
                E.author(author),
                E.pubDate(revision.created.strftime("%c")),
                E.link(h.absolute_url_for('page', id=page.urlTitle())),
                E.description(revision.comment or ''),
                E.category('wiki'),
            ))

        items.insert(0, E.title("Changes to page %s" % page.title))
        channel = E.channel(*items)
        rss = E.rss(channel, version="2.0")

        response.headers['Content-type'] = 'text/xml'

        return etree.tostring(rss, xml_declaration=True)


class RSSPlugin(Plugin):
    def __init__(self, **options):
        config['mtp.controllers']['rss'] = RSSController
        config['mtp.map'].pageConnect('page_rss', 'rss', 
            controller='rss', action='get')

        config['mtp.content.head'][('pages', 'show')].append(self.rsslink)

    def rsslink(self):
        url = h.url_for('page_rss', page_id=c.page.urlTitle())
        return '<link href="%s" rel="alternate" type="application/rss+xml" title="rss"/>' % url




